import { InteractionManager } from "react-native"

import { NavigationActions } from 'react-navigation'

export { default as Storage } from './Storage'

export { default as FN } from './Init'

export const delay = time => new Promise(resolve => setTimeout(resolve, time))

export const createAction = type => payload => ({ type, payload })

// 语言转换
export { default as LANG } from './Lang'

// 返回登录页
// export const gotoLogin = NavigationActions.reset({
//   index: 1,
//   actions: [
//     NavigationActions.navigate({ routeName: 'HomeNavigator' }),
//     NavigationActions.navigate({ routeName: 'Login' }),
//   ],
// })

// 详见 https://github.com/facebook/react-native/issues/15819
// v8 引擎与 JavaScriptCore 的区别, 不能直接 new Date()
export const jsCoreDateCreator = dateString => {
  if (!dateString) return ''
  // dateString *HAS* to be in this format "YYYY-MM-DD HH:MM:SS"
  const dateParam = dateString.split(/[\s-:]/)
  dateParam[1] = (parseInt(dateParam[1], 10) - 1).toString()
  return new Date(...dateParam)
}

// 数组对象深拷贝
export const deepCopy = (source) => {
  if (!source || typeof source !== 'object') {
    throw new Error('error arguments', 'shallowClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  for (let keys in source) {
    if (source.hasOwnProperty(keys)) {
      if (source[keys] && typeof source[keys] === 'object') {
        targetObj[keys] = deepCopy(source[keys])
      } else {
        targetObj[keys] = source[keys]
      }
    }
  }
  return targetObj
}

// ensure f get called, timeout at 500ms
// @gre workaround https://github.com/facebook/react-native/issues/8624
export const FixInteractionManager = {
  ...InteractionManager,
  runAfterInteractions: f => {
    let called = false
    const timeout = setTimeout(() => { called = true; f() }, 500)
    InteractionManager.runAfterInteractions(() => {
      if (called) return
      clearTimeout(timeout)
      f()
    })
  }
}


